package com.wave.web.controller.common;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wave.common.constant.CacheConstants;
import com.wave.common.constant.Constants;
import com.wave.common.core.domain.R;
import com.wave.common.enums.CaptchaType;
import com.wave.common.utils.StringUtils;
import com.wave.common.utils.email.MailUtils;
import com.wave.common.utils.redis.RedisUtils;
import com.wave.common.utils.reflect.ReflectUtils;
import com.wave.common.utils.spring.SpringUtils;
import com.wave.framework.config.properties.CaptchaProperties;
import com.wave.framework.config.properties.MailProperties;
import com.wave.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 验证码操作处理
 *
 * @author Lion Li
 */
@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class CaptchaController {

    private final CaptchaProperties captchaProperties;
    private final ISysConfigService configService;
    private final MailProperties mailProperties;

    /**
     * 短信验证码
     *
     * @param phonenumber 用户手机号
     */
    @GetMapping("/captchaSms")
    public R<Void> smsCaptcha(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
        String key = CacheConstants.CAPTCHA_CODE_KEY + phonenumber;
        String code = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        // 验证码模板id 自行处理 (查数据库或写死均可)
        String templateId = "";
        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
        map.put("code", code);
       /* SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
        SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, templateId, map);
        if (!"OK".equals(smsResponse.getCode())) {
            log.error("验证码短信发送异常 => {}", smsResponse);
            return R.fail(smsResponse.getMessage());
        }*/
        return R.ok();
    }

    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     */
    @GetMapping("/captchaEmail")
    public R<Void> emailCode(@NotBlank(message = "{user.email.not.blank}") String email) {
        if (!mailProperties.getEnabled()) {
            return R.fail("当前系统没有开启邮箱功能！");
        }
        String key = CacheConstants.CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        try {
            MailUtils.sendText(email, "登录验证码", "您本次验证码为：" + code + "，有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟，请尽快填写。");
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public R<Map<String, Object>> getCode() {
        Map<String, Object> ajax = new HashMap<>();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return R.ok(ajax);
        }
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        CaptchaType captchaType = captchaProperties.getType();
        boolean isMath = CaptchaType.MATH == captchaType;
        Integer length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
        CodeGenerator codeGenerator = ReflectUtils.newInstance(captchaType.getClazz(), length);
        AbstractCaptcha captcha = SpringUtils.getBean(captchaProperties.getCategory().getClazz());
        captcha.setGenerator(codeGenerator);
        captcha.createCode();
        String code = captcha.getCode();
        if (isMath) {
            ExpressionParser parser = new SpelExpressionParser();
            Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
            code = exp.getValue(String.class);
        }
        RedisUtils.setCacheObject(verifyKey, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        ajax.put("uuid", uuid);
        ajax.put("img", captcha.getImageBase64());
        return R.ok(ajax);
    }

    public static void main(String[] args) {
        String url = "http://10.78.105.253:9090/api/mes/produce/packCheck";
        JSONObject obj = new JSONObject();
        Map<String, String> map = new HashMap<>();
        //map.put("sn","010424H8TS20736196");
        //map.put("sn","010424H8TS20736196");
        map.put("sn","010424H89S30132219");
        obj.putOnce("data", map);
        String response = HttpUtil.createPost(url).setConnectionTimeout(2000).body(obj.toString()).execute().body();
        JSONObject respObj = JSONUtil.parseObj(response);
        String data = respObj.getStr("data");
        if (200 == Integer.parseInt(respObj.get("code") + "") && !com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(data)) {
            System.out.println(data);
        }

       /* HttpRequest request = HttpUtil.createPost("http://10.78.3.40:31873/api/base/Base_Information");
        request.header("Content-Type", "application/json");
        request.header("appId", "D026E0B4ADFC3469B204CF406AB77600");
        request.header("appKey","871B5E9BE6902EF977B525F0CA3EB75F");

        JSONObject obj = new JSONObject();
        obj.putOnce("factoryCode", "HFG4");
        obj.putOnce("serviceId", "Redirect001_simple");
        obj.putOnce("interfacecode", "Manufactures_Offline");
        obj.putOnce("taskId", DateUtils.dateTimeNowSSS());

        Map<String,Object> body = new HashMap<>();
        body.put("factoryCode", "HFG4");
        body.put("serviceId", "Redirect001_simple");
        body.put("taskId", DateUtils.dateTimeNowSSS());

        Map<String,Object> data = new HashMap<>();
        data.put("fromPointCode", "test_1025_3");//站点编码，AGV点位维护中的站点，对应AGV调度任务的起点
        data.put("materialCode", "4H8T");//产品类型
        data.put("containerCode", "DK0119R41560874");//物料编码
        data.put("quantity", 1);//物料数量
        data.put("lineCode", "*******");//产线编码
        data.put("stationCode", "*******");//工位编码
        data.put("packingRuleCode", "*******");//装箱规则编码
        data.put("packingHierarchy", "1");//装箱对象层
        List<String> snCodes = new ArrayList<>();
        snCodes.add("010424H8TS20736096");
        String snCodesStr = String.join(",", snCodes);
        data.put("snNumber", snCodesStr);//sn编码集合

        body.put("data",data);
        obj.putOnce("body",body);

        request.setConnectionTimeout(2000);//最长请求2s
        String response = request.body(obj.toString()).execute().body();
        JSONObject respObj = JSONUtil.parseObj(response);
        String respData = respObj.getStr("data");*/
    }
}
